<template>
  <div class="app-container">
    <!-- 查询和其他操作 -->
    <div class="filter-container">
      <el-button v-permission="['operation:goods:create']" class="filter-item" type="primary" icon="el-icon-edit" @click="handleCreate">添加</el-button>
    </div>

    <!-- 查询结果 -->
    <el-table
      v-loading="listLoading"
      :data="list"
      size="small"
      element-loading-text="正在查询中。。。"
      border
      fit
      highlight-current-row
      @selection-change="handleSelectionChange"
    >

      <el-table-column align="center" type="selection" width="55" />
      <el-table-column align="center" label="ID" prop="id" />

      <el-table-column align="center" min-width="100" label="节点名称" prop="title" />
      <el-table-column align="center" label="状态" prop="categoryId">
        <template slot-scope="scope">
          <el-tag >{{ scope.row.categoryId == 1 ? '节点' : '文件' }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center" min-width="100" label="序号" prop="num" />

      <!--
      <el-table-column align="center" min-width="100" label="所属项目" prop="shopId" />
-->

      <!--
      <el-table-column align="center" property="img" label="图片">
        <template slot-scope="scope">
          <img :src="scope.row.imgList[0]" width="40" >
        </template>
      </el-table-column>
-->

      <!--
      <el-table-column align="center" label="上传时间" prop="gmtCreate" />
--><!--

      <el-table-column align="center" label="操作人" prop="adminId" />
      <el-table-column
        align="center"
        max-width="300"
        min-width="300"
        label="描述"
        prop="description"
      />-->

      <el-table-column align="center" label="操作" width="250" class-name="small-padding fixed-width">
        <template slot-scope="scope">
<!--          <router-link :to="'/shopBiaozhun/shopBiaozhun?jiedianId='+scope.row.id">标准管理</router-link>
      -->    <el-button v-permission="['operation:goods:edit']" type="primary" size="mini" @click="handleUpdate(scope.row)">编辑</el-button>
          <el-button v-permission="['operation:goods:delete']" type="danger" style="margin:5px" size="mini" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.limit"
      @pagination="getList"
    />

    <el-tooltip placement="top" content="返回顶部">
      <back-to-top :visibility-height="100" />
    </el-tooltip>
  </div>
</template>

<script>
import { listGoods, deleteGoods, detailGoods, batchDeleteGoods, statistics } from '@/api/goods'
import BackToTop from '@/components/BackToTop'
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination

export default {
  name: 'GoodsList',
  components: { BackToTop, Pagination },
  data() {
    return {
      list: [],
      total: 0,
      goodsStatisticsCheckList: [40, 50, 70],
      listLoading: true,
      categoryOptions: [],
      goodsStatusMap: [{ value: 0, name: '下架' }, { value: 1, name: '正常' }],
      listQuery: {
        page: 1,
        limit: 20,
        shopId: undefined,
        title: undefined,
        status: undefined,
        barcode: undefined,
        categoryId: undefined
      },
      goodsDetail: '',
      detailDialogVisible: false,
      selectedIds: [],
      goodsStatisticsDialogVisible: false,
      goodsStatisticsTimePickModel: {},
      goodsStatisticsTimePickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
            picker.$emit('pick', [start, end])
          }
        }]
      }
    }
  },
  created() {
    this.listQuery.shopId = this.$route.query.shopId
    this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true
      listGoods(this.listQuery)
        .then(response => {
          response.data.data.items.forEach(item => {
            item.price = item.price / 100
            item.originalPrice = item.originalPrice / 100
            item.vipPrice = item.vipPrice / 100
            item.img
          })
          this.list = response.data.data.items
          this.total = response.data.data.total
          this.listLoading = false
        })
        .catch(() => {
          this.list = []
          this.total = 0
          this.listLoading = false
        })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    handleCreate() {
      this.$router.push({ path: '/sys/upsert' })
    },
    handleUpdate(row) {
      this.$router.push({ path: '/sys/upsert', query: { id: row.id }})
    },
    showDetail(row) {
      if (!this.detailDialogVisible) {
        detailGoods(row.id)
          .then(response => {
            this.goodsDetail = response.data.data.detail.replace(/<img/g, "<img style='max-width:100%;height:auto;line-height:0px'")
            this.detailDialogVisible = true
          })
      }
    },
    handleDelete(row) {
      this.$confirm('此操作将永久删除商品--' + row.title + '--, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteGoods(row.id)
          .then(response => {
            this.$notify.success({
              title: '成功',
              message: '删除成功'
            })
            const index = this.list.indexOf(row)
            this.list.splice(index, 1)
          })
          .catch(response => {
            this.$notify.error({
              title: '失败',
              message: response.data.errmsg
            })
          })
      }).catch(() => {
        return false
      })
    },
    handleSelectionChange(e) {
      const temp = []
      e.forEach(item => {
        temp.push(item.id)
      })
      this.selectedIds = temp
    },
    handleBatchDelete(e) {
      // 执行批量删除
      this.$confirm('此操作将永久删除选中的' + this.selectedIds.length + '件商品, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        batchDeleteGoods(this.selectedIds)
          .then(response => {
            this.$notify.success({
              title: '成功',
              message: '删除成功'
            })
            this.getList()
          })
          .catch(response => {
            this.$notify.error({
              title: '失败',
              message: response.data.errmsg
            })
          })
      }).catch(() => {
        return false
      })
    },
    showGoodsStatistics() {
      // 展示商品统计
      this.goodsStatisticsDialogVisible = true
      this.goodsStatisticsTimePickModel = {}
      this.goodsStatisticsCheckList = [40, 50, 70]
    },
    handleGoodsStatistics() {
      if (this.goodsStatisticsCheckList.length === 0) {
        this.$notify.error({
          title: '失败',
          message: '至少选择一种状态'
        })
      }
      // 构件请求参数
      const param = {}
      if (this.goodsStatisticsTimePickModel.length > 1) {
        // 若存在时间
        param['gmtStart'] = this.goodsStatisticsTimePickModel[0].getTime()
        param['gmtEnd'] = this.goodsStatisticsTimePickModel[1].getTime()
      }
      statistics(this.goodsStatisticsCheckList, this.selectedIds, param)
        .then(res => {
          res.data.data.forEach(item => {
            item.totalPrice = item.totalPrice / 100.0
            item.confirmPrice = item.confirmPrice / 100.0
            item.refundPrice = item.refundPrice / 100.0
          })
          this.handleDownload(res.data.data)
        })
        .catch(response => {
          this.$notify.error({
            title: '失败',
            message: response.data.errmsg
          })
        })
    },
    handleDownload(data) {
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = [
          'SPU_ID',
          'SPU标题',
          'SKU_ID',
          'SKU标题',
          '数量',
          '总金额',
          '确认金额',
          '退款金额'
        ]
        const filterVal = [
          'spuId',
          'spuTitle',
          'skuId',
          'skuTitle',
          'num',
          'totalPrice',
          'confirmPrice',
          'refundPrice'
        ]
        excel.export_json_to_excel2(tHeader, data, filterVal, '商品信息')
      })
    }
  }
}
</script>
